<template>
	<BasicModal @register="registerModalInner" title="编辑事件" width="800px" @ok="handleSubmit" @cancel="handleCancel">
		<div class="pt-12 flex justify-center">
			<BasicForm @register="registerForm"> </BasicForm>
		</div>
	</BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { BasicModal, BasicForm } from '#/components';
import { useForm, useModalInner } from '#/hooks';
import { useMessage } from '@/hooks/web/useMessage';
import { getSmallTypes } from '@/api/demo';

export default defineComponent({
	name: 'UseTableEditModal',
	components: { BasicModal, BasicForm },
	setup(_, { emit }) {
		let id = ref();

		const { createMessage } = useMessage();

		const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
			rowProps: { justify: 'center' },
			baseColProps: { span: 16 },
			showActionButtonGroup: false,
			schemas: [
				{
					field: 'number',
					label: '编号',
					component: 'Input',
					required: true,
				},
				{
					field: 'typeSmallId',
					label: '小类',
					component: 'ApiSelect',
					componentProps: {
						labelField: 'name',
						valueField: 'id',
						options: [],
					},
				},
				{
					field: 'createTime',
					label: '创建时间',
					component: 'DatePicker',
					required: true,
					componentProps: {
						valueFormat: 'YYYY-MM-DD',
					},
				},
				{
					field: 'reformFinish',
					label: '销项时间',
					component: 'DatePicker',
					required: true,
					componentProps: {
						valueFormat: 'YYYY-MM-DD',
					},
				},
			],
		});

		const [registerModalInner, { setModalProps, closeModal }] = useModalInner(async data => {
			resetFields();
			id.value = data.record.id;
			setFieldsValue({
				...data.record,
			});

			const options = await getSmallTypes(data.record?.typeBigId);

			updateSchema([
				{
					field: 'number',
					ifShow: !!data.record.number,
				},
				{
					field: 'typeSmallId',
					componentProps: { options },
				},
				{
					field: 'createTime',
					ifShow: !!data.record.createTime,
				},
				{
					field: 'reformFinish',
					ifShow: !!data.record.reformFinish,
				},
			]);
		});

		async function handleSubmit() {
			try {
				const values = await validate();
				setModalProps({ confirmLoading: true });
				values.id = id.value;

				console.log('submit values', values);

				closeModal();
				createMessage.success('操作成功');
				emit('success');
			} catch (error) {
				console.error(error);
				createMessage.error('操作失败');
			} finally {
				setModalProps({ confirmLoading: false });
			}
		}

		function handleCancel() {
			resetFields();
		}

		return {
			registerForm,
			registerModalInner,
			handleSubmit,
			handleCancel,
		};
	},
});
</script>
